// Login.tsx
import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import authManager from '../../utils/auth';
import styles from './Login.module.css';

const Login: React.FC = () => {
  const { t } = useTranslation('login');
  const [loading, setLoading] = useState(false);    //状态

  // 账号密码登录数据
  const [accountData, setAccountData] = useState({
    username: '',
    password: ''
  });

  const navigate = useNavigate();
  const API_BASE = '/api';  // 使用相对路径，自动适应不同设备访问

  // 账号密码登录
  const handleLoginWithAccount = async (e: React.FormEvent) => {
    e.preventDefault();
    setLoading(true);

    try {
      const response = await fetch(`${API_BASE}/auth/login`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: accountData.username,
          password: accountData.password
        }),
      });

      const data = await response.json();

      if (response.ok && data.success) {
        // 兼容后端返回的token字段
        const token = data.accessToken || data.token;
        console.log('登录成功，收到的token:', token ? `${token.substring(0, 20)}...` : '无token');
        console.log('收到的用户信息:', data.user);

        // 使用 authManager 保存认证信息
        if (token && data.user) {
          // 设置一个假的refreshToken，因为后端没有提供
          const fakeRefreshToken = `refresh-${token}`;
          authManager.setAuth(token, fakeRefreshToken, data.expiresIn || 86400000, data.user);
          // 同时保存token到localStorage，兼容旧代码
          localStorage.setItem('token', token);
          console.log('认证信息已保存');

          // 验证一下是否真的保存成功
          const savedToken = localStorage.getItem('token');
          const savedAccessToken = localStorage.getItem('accessToken');
          console.log('验证保存结果:', {
            token: !!savedToken,
            accessToken: !!savedAccessToken,
            user: !!localStorage.getItem('user')
          });

          alert(t('loginSuccess'));
          navigate('/admin');
        } else {
          console.error('登录响应缺少必要字段:', { token: !!token, user: !!data.user });
          alert('登录失败：响应数据不完整');
        }
      } else {
        console.error('登录失败:', data);
        alert(data.error || t('loginFailed'));
      }
    } catch (error) {
      console.error('登录失败:', error);
      alert(t('loginFailedNetwork'));
    } finally {
      setLoading(false);
    }
  };

  return (
    <div className={styles.container}>
      <div className={styles.box}>
        <h2 className={styles.title}>{t('title')}</h2>

        <form onSubmit={handleLoginWithAccount}>
          <div className={styles.formGroup}>
            <label className={styles.label}>{t('username')}</label>
            <input
              type="text"
              className={styles.input}
              value={accountData.username}
              onChange={(e) => setAccountData({ ...accountData, username: e.target.value })}
              placeholder={t('pleaseInputUsername')}
              required
            />
          </div>

          <div className={styles.formGroup}>
            <label className={styles.label}>{t('password')}</label>
            <input
              type="password"
              className={styles.input}
              value={accountData.password}
              onChange={(e) => setAccountData({ ...accountData, password: e.target.value })}
              placeholder={t('pleaseInputPassword')}
              required
            />
          </div>

          <button type="submit" className={styles.submitButton} disabled={loading}>
            {loading ? t('loggingIn') : t('loginWithAccount')}
          </button>
        </form>
      </div>
    </div>
  );
};

export default Login;